//
//  HttpTool.m
//  05-二次封装AFN
//
//  Created by 大欢 on 16/8/4.
//  Copyright © 2016年 大欢. All rights reserved.
//

#import "HttpTool.h"
#import "AFNetworking/AFNetworking.h"

static NSString * kBaseUrl = SERVER_HOST;

@interface AFHttpClient : AFHTTPSessionManager

+ (instancetype)sharedClient;

@end

static AFHttpClient * client = nil;

@implementation AFHttpClient


//原封装
+ (instancetype)sharedClient {
    
    static AFHttpClient * client = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        NSURLSessionConfiguration * configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
        client = [[AFHttpClient alloc] initWithBaseURL:[NSURL URLWithString:kBaseUrl] sessionConfiguration:configuration];
        AFJSONResponseSerializer *response = [AFJSONResponseSerializer serializer];
        response.removesKeysWithNullValues = YES;
        client.responseSerializer = response;
        //接收参数类型
        client.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html", @"text/json", @"text/javascript",@"text/plain",@"image/gif",@"image/jpeg",@"image/png",@"application/octet-stream", nil];
        //设置超时时间
        client.requestSerializer.timeoutInterval = 15;
        //安全策略
        client.securityPolicy = [AFSecurityPolicy defaultPolicy];
    
        
    });
    NSString *token = [LTools cacheForKey:SERVER_LoginToken];
    if (token.length < 1)
    {
        token = @"";
    }
    [client.requestSerializer setValue:token forHTTPHeaderField:@"token"];

    return client;
}



@end

@implementation HttpTool

+ (void)getWithPath:(NSString *)path
             params:(NSDictionary *)params
            success:(HttpSuccessBlock)success
            failure:(HttpFailureBlock)failure {
    //获取完整的url路径
    NSString * url = [kBaseUrl stringByAppendingPathComponent:path];
    
    [[AFHttpClient sharedClient] GET:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        success(responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        failure(error);
        
    }];
}

+ (void)postWithPath:(NSString *)path
             params:(NSDictionary *)params
            success:(HttpSuccessBlock)success
            failure:(HttpFailureBlock)failure {
    
    //获取完整的url路径
    NSString * url = [kBaseUrl stringByAppendingPathComponent:path];
    //NSString * url = [kBaseUrl stringByAppendingString:path];
    
    //封装token
    
    
    //请求回调
//    [MBProgressHUD showHUDAddedTo:sharedDelegate.window animated:YES];
    
    [[AFHttpClient sharedClient] POST:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        [MBProgressHUD hideAllHUDsForView:sharedDelegate.window animated:YES];

        success(responseObject);
        if ([responseObject[@"code"] integerValue] == 444)
        {
            NSLog(@"======%@=====",url);
            [LTools storage:NO ForKey:SERVER_IsLogin];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        [MBProgressHUD hideAllHUDsForView:sharedDelegate.window animated:YES];

        failure(error);
        
    }];
    
    
}


//json
+ (void)postWithPathJson:(NSString *)path
                  params:(id)params
                 success:(HttpSuccessBlock)success
                 failure:(HttpFailureBlock)failure {
    
    //获取完整的url路径
    NSString * url = [kBaseUrl stringByAppendingPathComponent:path];
    NSURLSessionConfiguration * configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    
    AFHttpClient * client  = [[AFHttpClient alloc] initWithBaseURL:[NSURL URLWithString:kBaseUrl] sessionConfiguration:configuration];
    AFJSONResponseSerializer *response = [AFJSONResponseSerializer serializer];
    response.removesKeysWithNullValues = YES;
    client.responseSerializer = response;
    //接收参数类型
    client.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html", @"text/json", @"text/javascript",@"text/plain",@"image/gif",@"image/jpeg",@"image/png",@"application/octet-stream", nil];
    //设置超时时间
    client.requestSerializer.timeoutInterval = 15;
    //安全策略
    client.securityPolicy = [AFSecurityPolicy defaultPolicy];
    //申明请求的数据是json类型
    client.requestSerializer = [AFJSONRequestSerializer serializer];
    NSString *token = [LTools cacheForKey:SERVER_LoginToken];
    if (token.length < 1)
    {
        token = @"";
    }
    [client.requestSerializer setValue:token forHTTPHeaderField:@"token"];
    
//    [MBProgressHUD showHUDAddedTo:sharedDelegate.window animated:YES];

    [client POST:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        [MBProgressHUD hideAllHUDsForView:sharedDelegate.window animated:YES];

        success(responseObject);
        if ([responseObject[@"code"] integerValue] == 444)
        {
            NSLog(@"======%@=====",url);
            [LTools storage:NO ForKey:SERVER_IsLogin];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        [MBProgressHUD hideAllHUDsForView:sharedDelegate.window animated:YES];

        failure(error);
        
    }];
    
}
    


//带参数
+ (void)postWithPathAndParams:(NSString *)path
              params:(NSDictionary *)params
             success:(HttpSuccessBlock)success
             failure:(HttpFailureBlock)failure {
    //获取完整的url路径
    //NSString * url = [kBaseUrl stringByAppendingPathComponent:path];
    NSString * url = [kBaseUrl stringByAppendingString:path];
    NSString * parth=@"";
    
    id key, value;
    
    NSArray *keys = [params allKeys];//获取字典中的数组
    
    for (NSInteger i = 0; i < [params allKeys].count; i++)
    {
        key = [keys objectAtIndex: i];
        value = [params objectForKey: key];
        
        if (i==0) {
            
            parth = [parth stringByAppendingFormat:@"%@=%@",key, value];
            
        }else{
            
            parth = [parth stringByAppendingFormat:@"&%@=%@",key, value];
        }
        
        //NSLog (@"Key: %@ for value: %@", key, value);
    }
    
    url = [url stringByAppendingString:@"?"];
    url = [url stringByAppendingString:parth];
    
    //[_manager.requestSerializer setValue: [NSString stringWithFormat:@"Bearer %@", token] forHTTPHeaderField:@"Authorization"];
    //
    
    //封装token
//    if (headDic.count) {
//        
//        [headDic enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
//            
//            [[AFHttpClient sharedClient].requestSerializer setValue:obj forHTTPHeaderField:key];
//            
//        }];
//    }
    
    //请求回调  将parameters的中的字典遍历出来拼接到url中
    [[AFHttpClient sharedClient] POST:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        success(responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        failure(error);
        
    }];
    
    
}

+ (void)downloadWithPath:(NSString *)path
                 success:(HttpSuccessBlock)success
                 failure:(HttpFailureBlock)failure
                progress:(HttpDownloadProgressBlock)progress {
    
    //获取完整的url路径
    NSString * urlString = [kBaseUrl stringByAppendingPathComponent:path];
    
    //下载
    NSURL *URL = [NSURL URLWithString:urlString];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    
    NSURLSessionDownloadTask *downloadTask = [[AFHttpClient sharedClient] downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        
        progress(downloadProgress.fractionCompleted);
        
    } destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
        
        //获取沙盒cache路径
        NSURL * documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSCachesDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
        
        return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
        
        
    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
        
        if (error) {
            failure(error);
        } else {
            success(filePath.path);
        }
        
    }];
    
    [downloadTask resume];
    
}

+ (void)uploadImageWithPath:(NSString *)path
                     params:(NSDictionary *)params
                  thumbName:(NSString *)imagekey
                      image:(UIImage *)image
                    success:(HttpSuccessBlock)success
                    failure:(HttpFailureBlock)failure
                   progress:(HttpUploadProgressBlock)progress {
    //以文件流的格式上传图片
    //获取完整的url路径
    NSString * urlString = [kBaseUrl stringByAppendingPathComponent:path];
    
    //PNG格式
    //NSData * data = UIImagePNGRepresentation(image);
    
    //JPEG
    NSData * data = UIImageJPEGRepresentation(image, 0.4);
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat       = @"yyyyMMddHHmmss";
    NSString *str              = [formatter stringFromDate:[NSDate date]];
    NSString *fileName         = [NSString stringWithFormat:@"%@.jpg", str];
    
    [[AFHttpClient sharedClient] POST:urlString parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        // name:@"file"
        [formData appendPartWithFileData:data name:imagekey fileName:fileName mimeType:@"image/jpeg"];//@"01.png" @"image/png"
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        //progress(uploadProgress.fractionCompleted);
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        success(responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        failure(error);
        
    }];
}

 + (void)uploadImageWithPath:(NSString *)path
                       params:(NSDictionary *)params
                    thumbName:(NSString *)imagekey
                        ImageAry:(NSArray *)imageAry
                      success:(HttpSuccessBlock)success
                      failure:(HttpFailureBlock)failure
                     progress:(HttpUploadProgressBlock)progress
{
    NSString * urlString = [kBaseUrl stringByAppendingPathComponent:path];
    // 在parameters里存放照片以外的对象
    [[AFHttpClient sharedClient] POST:urlString parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        // formData: 专门用于拼接需要上传的数据,在此位置生成一个要上传的数据体
        // 这里的_photoArr是你存放图片的数组
        for (int i = 0; i < imageAry.count; i++) {
            
            UIImage *image = imageAry[i];
            NSData *imageData = UIImageJPEGRepresentation(image, 0.4);
            
            // 在网络开发中，上传文件时，是文件不允许被覆盖，文件重名
            // 要解决此问题，
            // 可以在上传时使用当前的系统事件作为文件名
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            // 设置时间格式
            [formatter setDateFormat:@"yyyyMMddHHmmss"];
            NSString *dateString = [formatter stringFromDate:[NSDate date]];
            NSString *fileName = [NSString stringWithFormat:@"%@.jpg", dateString];
            /*
             *该方法的参数
             1. appendPartWithFileData：要上传的照片[二进制流]
             2. name：对应网站上[upload.php中]处理文件的字段（比如upload）
             3. fileName：要保存在服务器上的文件名
             4. mimeType：上传的文件的类型
             */
            [formData appendPartWithFileData:imageData name:imagekey fileName:fileName mimeType:@"image/jpeg"]; //
        }
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        NSLog(@"---上传进度--- %@",uploadProgress);
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSLog(@"```上传成功``` %@",responseObject);
        success(responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"xxx上传失败xxx %@", error);
        failure(error);
        
    }];
}


@end
